﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EDiamondModel;
public partial class Admin_ThanhPho : System.Web.UI.Page
{
    EDiamondEntities1 db = new EDiamondEntities1();
    void LoadThanhPho()
    {
        gvThanhPho.DataKeyNames = new string[] { "Id" };
        var query = db.ThanhPhoes;
        gvThanhPho.DataSource = query;
        gvThanhPho.DataBind();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadThanhPho();
        }
    }
    protected void gvThanhPho_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvThanhPho.EditIndex = -1;
        LoadThanhPho();
    }
    protected void gvThanhPho_RowCreated(object sender, GridViewRowEventArgs e)
    {

    }
    protected void gvThanhPho_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int khoa = Int32.Parse(gvThanhPho.DataKeys[e.RowIndex].Value.ToString());
        try
        {

            ThanhPho entity = db.ThanhPhoes.Include("Nuocs").SingleOrDefault(p => p.Id == khoa);

            db.ThanhPhoes.DeleteObject(entity);
            db.SaveChanges();
            lbThongBao.Text = "Hủy thành công";
            LoadThanhPho();
        }
        catch (Exception ex)
        {
            lbThongBao.Text = "Hủy không thành công";
        }
    }
    protected void gvThanhPho_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string ten = ((TextBox)gvThanhPho.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
        string ma = ((TextBox)gvThanhPho.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
        if (!string.IsNullOrEmpty(ten))
        {
            try
            {
                Int16 khoa = System.Convert.ToInt16(gvThanhPho.DataKeys[e.RowIndex].Value);
                ThanhPho entiry = db.ThanhPhoes.FirstOrDefault(p => p.Id == khoa);
                entiry.TenThanhPho = ten;
                entiry.IdNuoc = Int32.Parse(ma);
                

                db.SaveChanges();

                gvThanhPho.EditIndex = -1;
                lbThongBao.Text = "Cập nhật thành công!";
                LoadThanhPho();
            }
            catch (Exception ex)
            {
                lbThongBao.Text = "Cập nhật không thành công!" + ex.Message;
            }
        }
        else
            e.Cancel = true;
    }
    protected void gvThanhPho_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvThanhPho.EditIndex = e.NewEditIndex;
        LoadThanhPho();
    }
}